package com.dm.shop.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dm.shop.common.enums.ResultEnum;
import com.dm.shop.dto.CProductDTO;
import com.dm.shop.entity.Category;
import com.dm.shop.entity.Product;
import com.dm.shop.entity.ProductImage;
import com.dm.shop.service.CategoryService;
//import com.ctgu.fmall.service.searchService;
import com.dm.shop.service.ProductImageService;
import com.dm.shop.service.ProductService;
import com.dm.shop.service.SearchService;
import com.dm.shop.utils.ResultUtil;
import com.dm.shop.vo.ProductVO;
import com.dm.shop.vo.Result;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author MyBatisPlusGenerater-Saiya Wang
 * @since 2021-07-20
 */
@RestController
@Slf4j
@RequestMapping("/product")
@CrossOrigin
public class ProductController {
    @Autowired
    ProductService productService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    ProductImageService productImageService;

    @Autowired
    SearchService searchService;

    @GetMapping("{pageNo}/{pageSize}/{cid}")
    public Result getProductByPage(@PathVariable("pageNo") Integer pageNo,@PathVariable("pageSize") Integer pageSize,@PathVariable("cid") int cid) throws IOException{
        IPage page = new Page<Product>(pageNo,pageSize);
        QueryWrapper<Product> wrapper= new QueryWrapper<>();
        IPage oldPage=productService.page(page,wrapper);
        List<Product>productList=oldPage.getRecords();
        List<ProductVO>productVOS=new ArrayList<>();
        HashMap hashMap=new HashMap();
        if(productList.size()==0){
            hashMap.put("list",productVOS);
            hashMap.put("total",oldPage.getTotal());
            ResultUtil.success(hashMap);
        }
        for(Product p:productList){
            log.info(p.toString());
            QueryWrapper<ProductImage> imageQueryWrapper = new QueryWrapper<>();
            imageQueryWrapper.eq("pid",p.getId());
            List<ProductImage>productImages=productImageService.list(imageQueryWrapper);
            if(productImages.size()>0){
                ArrayList<String> imgUrls = new ArrayList<>();
                imgUrls.add(productImages.get(0).getImgUrl());
                ProductVO productVO = new ProductVO(p,imgUrls);
                productVOS.add(productVO);
            }
        }
        hashMap.put("list",productVOS);
        hashMap.put("total",oldPage.getTotal());
        return ResultUtil.success(hashMap);
    }

    @GetMapping("/keysearch/{keyword}")
    @ApiOperation("根据关键词搜索")
    public Result keySearch(String keyword){
        QueryWrapper<Product> wrapper=new QueryWrapper<>();
        wrapper.like("name",keyword);
        List<Product> product = productService.list(wrapper);
        List<ProductVO> productVOList=new ArrayList<>();
        if(product==null){
            return ResultUtil.error(ResultEnum.NOT_FOUND);
        }
        for(Product product1:product)
        {
            QueryWrapper<ProductImage> imageQueryWrapper = new QueryWrapper<>();
            imageQueryWrapper.eq("pid",product1.getId());
            List<ProductImage> productImages= productImageService.list(imageQueryWrapper);
            if(productImages.size()>0) {
                ArrayList<String> imgUrls = new ArrayList<>();
                imgUrls.add(productImages.get(0).getImgUrl());
                ProductVO productVO = new ProductVO(product1, imgUrls);
                productVOList.add(productVO);
            }else {
                ProductVO productVO = new ProductVO(product1, null);
                productVOList.add(productVO);
            }

        }
        return ResultUtil.success(productVOList);
    }

    @GetMapping("/search/{keyword}/{pageNo}/{pageSize}/{cid}")
    public Result search(@PathVariable String keyword,@PathVariable int pageNo, @PathVariable int pageSize, @PathVariable int cid) throws IOException {
        log.info("搜索词：{}，页码：{}，页数：{},分类ID：{}",keyword,pageNo,pageSize,cid);
        log.info("搜索情况!!!!");
        HashMap map =searchService.searchProduct(keyword,pageNo,pageSize,cid);
        log.info("搜索情况："+map);
        return ResultUtil.success(map);
    }

    @GetMapping("/allinCate")
    @ApiOperation("获取所有目录以及目录下面的所有商品")
    public Result getAllPInC(){
        /**
         * 获取所有目录
         */
        List<Category> clist = categoryService.list(null);
        /**
         * 存放要返回的内容，及商品种类及商品的列表
         */
        List<CProductDTO> list= new ArrayList<>();
        for(int i=0;i<clist.size();i++){
            /**
             * 存放每种商品要展示的内容，是所有的商品
             */
            List<ProductVO> productVOS=new ArrayList<>();
            /**
             * 获取该商品种类下的所有的product
             */
            QueryWrapper<Product> wrapper = new QueryWrapper<>();
            wrapper.eq("cid",clist.get(i).getId());
            List<Product> plist= productService.list(wrapper);
            for(Product p:plist){
                /**
                 * 为该商品创建一个vo
                 */
                QueryWrapper<ProductImage> imageQueryWrapper = new QueryWrapper<>();
                imageQueryWrapper.eq("pid",p.getId());
                List<ProductImage> productImages= productImageService.list(imageQueryWrapper);
                if(productImages.size()>0){
                    ArrayList<String> imgUrls = new ArrayList<>();
                    imgUrls.add(productImages.get(0).getImgUrl());
                    ProductVO productVO = new ProductVO(p,imgUrls);
                    productVOS.add(productVO);
                }
                else {
                    ProductVO productVO = new ProductVO(p,null);
                    productVOS.add(productVO);
                }

            }
            CProductDTO cProductDTO=new CProductDTO(clist.get(i).getName(),productVOS);
            list.add(cProductDTO);
        }

        return ResultUtil.success(list);

    }

    @GetMapping("/num")
    @ApiOperation("获取每类的商品数量和类名")
    public Result getNumByCategory(){
        /**
         * 获取所有目录
         */
        List<Category> clist = categoryService.list(null);
        List<Map> numList = new ArrayList<>();
        List<CProductDTO> list= new ArrayList<>();
        for (Category c: clist) {
            QueryWrapper<Product> wrapper = new QueryWrapper<>();
            wrapper.eq("cid", c.getId());
            List<Product> plist = productService.list(wrapper);
            Map temp = new HashMap();
            temp.put("cname", c.getName());
            temp.put("num", plist.size());
            numList.add(temp);
        }
        return ResultUtil.success(numList);
    }

    @GetMapping("/top5")
    @ApiOperation("月销排名前5的商品")
    public Result listTop5(){
        QueryWrapper<Product> wrapper =new QueryWrapper<>();
        wrapper.orderByDesc("sale_num")
                .last("limit 5");
        List<Product> plist=  productService.list(wrapper);
        List<ProductVO> productVOS=new ArrayList<>();
        for (Product p: plist ) {
            QueryWrapper<ProductImage> imageQueryWrapper = new QueryWrapper<>();
            imageQueryWrapper.eq("pid",p.getId());
            List<ProductImage> productImages= productImageService.list(imageQueryWrapper);
            if(productImages.size()>0){

                ArrayList<String> imgUrls = new ArrayList<>();
                imgUrls.add(productImages.get(0).getImgUrl());
                ProductVO productVO = new ProductVO(p,imgUrls);
                productVOS.add(productVO);
            }
        }
        return ResultUtil.success(productVOS);
    }

    @GetMapping("/{id}")
    @ApiOperation("通过商品编号获得商品详情")
    public Result getProductByid(@PathVariable int id){
        QueryWrapper<Product> wrapper=new QueryWrapper<>();
        wrapper.eq("id",id);
        Product product = productService.getOne(wrapper);
        if(product==null){
            return ResultUtil.error(ResultEnum.NOT_FOUND);
        }
        QueryWrapper<ProductImage> imageQueryWrapper = new QueryWrapper<>();
        imageQueryWrapper.eq("pid",product.getId());
        List<ProductImage> productImages= productImageService.list(imageQueryWrapper);
        if(productImages.size()>0) {
            ArrayList<String> imgUrls = new ArrayList<>();
            imgUrls.add(productImages.get(0).getImgUrl());
            ProductVO productVO = new ProductVO(product, imgUrls);
            return ResultUtil.success(productVO);
        }else {
            ProductVO productVO = new ProductVO(product, null);
            return ResultUtil.success(productVO);
        }
    }

    @PostMapping("/add")
    @ApiOperation("添加商品")
    public Result AddProduct(@RequestBody ProductVO productVO)
    {
        Product product=new Product(productVO);
        productService.save(product);
        System.out.println("id："+product.getId());
        Integer pid = product.getId();
        boolean isSave = false;
        for (Integer i = 0;i < productVO.getImgUrl().size();i++)
        {
            ProductImage productImage = new ProductImage();
            productImage.setImgUrl(productVO.getImgUrl().get(i));
            productImage.setPid(pid);
            isSave = productImageService.save(productImage);
        }
        if (isSave == true)
            return ResultUtil.success(ResultEnum.SUCCESS);
        return ResultUtil.error(ResultEnum.FAIL);
    }

    @DeleteMapping("/del/{id}")
    @ApiOperation("根据商品id删除商品及其图片")
    public Result delProduct(@PathVariable("id") Integer id)
    {
        boolean isDel = productService.removeById(id);
        QueryWrapper<ProductImage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pid",id);
        if(isDel == true)
        {
            List<ProductImage> productImages = productImageService.list(queryWrapper);
            if (productImages != null)
            {
                boolean isDelImage = productImageService.remove(queryWrapper);
                if (isDelImage == true)
                {
                    return ResultUtil.success(ResultEnum.SUCCESS);
                }
                return ResultUtil.error(ResultEnum.FAIL);
            }
            return ResultUtil.success(ResultEnum.SUCCESS);
        }
        return ResultUtil.error(ResultEnum.FAIL);
    }
}
